package com.glory.dgcpcpda.activity.mfg;

import android.os.Handler;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.AddCarrierDataAdapter;
import com.glory.dgcpcpda.adapter.MaterielListAdapter;
import com.glory.dgcpcpda.adapter.PartListAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.callback.CustomDialogEntityCallBack;
import com.glory.dgcpcpda.entity.AdrefListEntity;
import com.glory.dgcpcpda.entity.LotInfoEntity;
import com.glory.dgcpcpda.entity.LotList;
import com.glory.dgcpcpda.entity.MaterielListEntity;
import com.glory.dgcpcpda.entity.PrintEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * FileName: DAWorkBeginActivity
 * Author: XJH
 * Date: 2020/5/21 9:05
 * Description:开始作业DA工序
 * History:
 */
public class DAWorkBeginActivity extends BaseActivity {
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.tvLotState)
    TextView tvLotState;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.etEqpWorkID)
    FreeUI_ClearEditText etEqpWorkID;
    @BindView(R.id.tvBDNum)
    TextView tvBDNum;
    @BindView(R.id.tvRecipeID)
    TextView tvRecipeID;
    @BindView(R.id.rvMaterielList)
    RecyclerView rvMaterielList;
    @BindView(R.id.list_tv1)
    TextView listTv1;
    @BindView(R.id.list_tv2)
    TextView listTv2;
    @BindView(R.id.list_tv3)
    TextView listTv3;
    @BindView(R.id.list_tv4)
    TextView listTv4;
    @BindView(R.id.list_tv5)
    TextView listTv5;
    @BindView(R.id.rvPartList)
    RecyclerView rvPartList;
    @BindView(R.id.etComment)
    FreeUI_ClearEditText etComment;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.etUserName)
    FreeUI_ClearEditText etUserName;
    @BindView(R.id.llCarrierLayout)
    LinearLayout llCarrierLayout;
    @BindView(R.id.etBingLotID)
    EditText etBingLotID;
    @BindView(R.id.tvBingLotID)
    TextView tvBingLotID;
    @BindView(R.id.rvLotList)
    RecyclerView rvLotList;
    private MaterielListAdapter materielListAdapter;
    private List<MaterielListEntity.Materiel> materielList;
    private List<MaterielListEntity.Materiel> partList;
    private PartListAdapter partListAdapter;
    private AddCarrierDataAdapter carrierAdapter;
    private List<String> carrierList = new ArrayList<>();
    private String customercode = "";
    private String chipname = "";

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_track_in_da;
    }

    @Override
    protected void initView() {
        initLayout();
        llCarrierLayout.setVisibility(View.GONE);
        initEdit(etLot, s -> {
            //获取lot信息
            LotUtils.searchLotInfo(DAWorkBeginActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @Override
                public void onSuccess(LotInfoEntity response) {
                    if(!response.getLOT().getSTEPDESC().contains("装片")){
                        showConfirmDialog("非装片工序请用[开始作业]进站");
                        return;
                    }
                    tvBDNum.setText(response.getWIRINGNO());
                    tvTitle.setText("DA开始作业" + "(" + response.getLOT().getSTEPDESC() + ")");
                    String state = response.getLOT().getSTATE();
                    if(state.equals("正在作业")){
                        state = state + " - " + response.getLOT().getEQUIPMENTID();
                    }
                    customercode = response.getLOT().getCUSTOMERCODE();//客户号
                    chipname = response.getCHIPNAME();//芯片名
                    tvLotState.setText(state);
                    showCarrierLayout(response);
                    carrierList.clear();
                    carrierList.addAll(response.getDURABLELIST());
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t,"LOTQUERY");
                }

            });
        });

        initEdit(etEqpWorkID, s -> {
            partList.clear();
            materielList.clear();
            getKittingInfo(s);
        });

        initEdit(etBingLotID,s ->{
            new Handler().postDelayed(() -> etBingLotID.setText(""),500);
            if (carrierList.contains(s) && !carrierAdapter.getData().contains(s)){
                carrierAdapter.addData(s);
            }else {
                showToast("请扫描正确的载具",false);
            }
        });
    }

    private void showCarrierLayout(LotInfoEntity data) {
        FreeUI_EntityCallBack<BaseResponseBean<AdrefListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<AdrefListEntity>>
                (new TypeToken<BaseResponseBean<AdrefListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    List<AdrefListEntity.Adref> adreflist = response.body().getResponse().getBody().getADREFLIST();
                     for (AdrefListEntity.Adref entity : adreflist) {
                        if (entity.getTEXT().equals(data.getLOT().getSTEPNAME())  && entity.getDESCRIPTION().equals(data.getPACKAGETYPE())) {
                           llCarrierLayout.setVisibility(View.VISIBLE);
                            tvBingLotID.setText("料框/料盒：");
                            etBingLotID.setHint("请扫描料框/料盒");
                           return;
                        }
                    }

                    llCarrierLayout.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"ADREFLISTQUERY");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("REFERENCETYPE","USER");
        map.addProperty("REFERENCENAME","CPC_CARRIERS_CHECK_STEP");
        NetUtils.requestPostNet("CPC.ADREFLISTQUERY","ADREFLISTQUERY",this,map,callBack);
    }

    private void getKittingInfo(String eqpID) {
        FreeUI_EntityCallBack<BaseResponseBean<MaterielListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<MaterielListEntity>>
                (new TypeToken<BaseResponseBean<MaterielListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<MaterielListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(DAWorkBeginActivity.this,true,getSupportFragmentManager())){
                    List<MaterielListEntity.Materiel> mlotlist = response.body().getResponse().getBody().getMLOTLIST();
                    for (MaterielListEntity.Materiel data : mlotlist){
                        if (data.getMATERIALTYPE().equals("WAFER")){
                            partList.add(data);
                        }else {
                            materielList.add(data);
                        }
                    }
                    materielListAdapter.setNewData(materielList);
                    partListAdapter.setNewData(partList);
                }

            }

            @Override
            public void onError(Response<BaseResponseBean<MaterielListEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"MLOTKITTING");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE","LOAD");
        map.addProperty("EQUIPMENTID",eqpID);
        NetUtils.requestPostNet("MES.MLOTKITTING","MLOTKITTING",DAWorkBeginActivity.this,map,callBack);
    }



    private  void Submit(){
        if (actionControl("Submit01")){
            return;
        }

        if (tvLotState.getText().toString().equals("待投产")){
            showConfirmDialog("批次未投产，请联系计划部执行投产");
            return;
        }

        if (tvLotState.getText().toString().contains("正在作业")){
            showConfirmDialog("批次正在作业，请直接操作出站功能");
            return;
        }

        if (getText(etUserName).equals("")){
            showToast("请输入工号",false);
            return;
        }

        if (carrierAdapter.getData().size() != carrierList.size() && llCarrierLayout.getVisibility() == View.VISIBLE){
            showToast("载具验证未完成",false);
            return;
        }

        LotUtils.lotTrackIn(getSupportFragmentManager(),this,getText(etUserName),getText(etEqpWorkID),getText(etLot),carrierAdapter.getData(),"DefaultTrackIn");
    }

    private void initLayout() {
        tvTitle.setText("DA开始作业");
        listTv1.setText("No.");
        listTv2.setText("芯片料号");
        listTv3.setText("芯片批号");
        listTv4.setText("芯片片号");
        listTv5.setText("芯片型号");
        listTv5.setVisibility(View.VISIBLE);
        setMainLayout(llMain);
        initRecyclerView(rvMaterielList,this);
        initRecyclerView(rvPartList,this);
        initRecyclerView(rvLotList,this);
        carrierAdapter = getCarrierAdapter();
        rvLotList.setAdapter(carrierAdapter);
        materielListAdapter = new MaterielListAdapter(null);
        materielListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        materielListAdapter.isFirstOnly(true);
        rvMaterielList.setAdapter(materielListAdapter);

        partListAdapter = new PartListAdapter(null);
        partListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        partListAdapter.isFirstOnly(true);
        rvPartList.setAdapter(partListAdapter);

        materielList = new ArrayList<>();
        partList = new ArrayList<>();

        customercode = "";
        chipname = "";

    }

    @Override
    protected void initData() {

    }

    @OnClick(R.id.tvBaseSubmit)
    public void onViewClicked() {

//        if(!getText(etEqpWorkID).equals("")||!customercode.equals("")||!chipname.equals("")){
//            FreeUI_EntityCallBack<BaseResponseBean<PrintEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<PrintEntity>>
//                    (new TypeToken<BaseResponseBean<PrintEntity>>() {
//                    }.getType(), getSupportFragmentManager(), this) {
//
//                @Override
//                public void onSuccess(Response<BaseResponseBean<PrintEntity>> response) {
//                    super.onSuccess(response);
//                    if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
//
//                    }
//                }
//
//                @Override
//                public void onError(Response<BaseResponseBean<PrintEntity>> response) {
//                    super.onError(response);
//                    loadError(response.getException(), "DaemonUpdateType");
//                }
//            };
//            JsonObject map = new JsonObject();
//            map.addProperty("ActionName","Check");
//            map.addProperty("EQP_ID",getText(etEqpWorkID));
//            map.addProperty("CUSTOMER_CODE",customercode);
//            map.addProperty("CHIP_NAME",chipname);
//            NetUtils.requestPostNet("CPC.MapSpecification", "MapSpecification", this, map, callBack);
//        }
        Submit();
//        else {
//            Submit();
//        }
    }


}
